<?php

class Table
{
    var $redis_;
    var $pdo = null;
    var $logger = null;

    function __construct()
    {
        $this->redis_ = null;
        $this->pdo = PDOWrapper::instance();
        $this->logger = CLog::getInstance();
    }

    function __destruct()
    {
        if($this->redis_ != null) {
            $this->redis_->close();
        }
    }

    //获取该桌订单接口
    function TableV1($GetParams, $PostArray){

        $user_info = User::GetInfoByToken($GetParams['token']);
        if($user_info === false) {
            return false;
        }

        $table = self::get_order($user_info['r_id'],$user_info['table_id']);
        if ($table === false) {
            return false;
        }

        $table_list = [];
        $table_list = self::sort_type($table,$table_list);
        $table_info = self::table_info($user_info);
       

        $message = [
            'table' => $table_list,
            'users_num' => $table_info['users_num'],
            'note' => $table_info['note']
        ];
        Utils::ShowMessage($message);
        return true;
    }

    function sort_type($table,$table_list = array()){
        if (empty($table)) {
            return $table_list;
        }
        if (empty($table_list)) {
            $table_list[0]['type_id'] = $table[0]['type_id'];
            $table_list[0]['type_name'] = $table[0]['type_name'];
            $table_list[0]['list'] = [];
            array_push($table_list[0]['list'], $table[0]);
            array_splice($table, 0, 1);
            return self::sort_type($table,$table_list);
        }
        
        $flag = false;
        foreach ($table_list as $key => $value) {
            
            if ($value['type_id'] == $table[0]['type_id']) {
                $flag = true;
                array_push($table_list[$key]['list'], $table[0]);
                array_splice($table, 0, 1);
                break;
            }
        }
        $temp = [];
        if ($flag === false) {
            $temp['type_id'] = $table[0]['type_id'];
            $temp['type_name'] = $table[0]['type_name'];
            $temp['list'] = [];
            array_push($temp['list'], $table[0]);
            array_push($table_list, $temp);
            array_splice($table, 0, 1);
        }
        return self::sort_type($table,$table_list);
    }

    //改变订单数
    function ChangeOrderV1($GetParams, $PostArray){

        $user_info = User::GetInfoByToken($GetParams['token']);
        if($user_info === false) {
            return false;
        }

        if (!isset($GetParams['order_num'])) {
            Utils::ShowError(ErrorDefine::ILLEGALL_OF_ORDERNUM);
            return false;
        }

        if (!isset($GetParams['recipe_id'])) {
            Utils::ShowError(ErrorDefine::SHORT_OF_RECIPEID);
            return false;
        }
        $check_num = $this->pdo->select('recipe_detail',array('d_num'),array('recipe_id' => $GetParams['recipe_id']));
        if ($check_num === false) {
            Utils::ShowError(ErrorDefine::SELECT_TABLE_FAILED);
            return false;
        }

        $table = self::get_order($user_info['r_id'],$user_info['table_id']);
        if ($table === false) {
            return false;
        }

        if ($GetParams['order_num']>$check_num[0]['d_num']) {
            Utils::ShowError(ErrorDefine::ILLEGALL_OF_ORDERNUM);
            return false;
        }

        foreach ($table as $key => $value) {
            if ($value['recipe_id'] == $GetParams['recipe_id']) {
                $table[$key]['order_num'] = $GetParams['order_num'];
                if ($table[$key]['order_num'] > $check_num[0]['d_num']) {
                    Utils::ShowError(ErrorDefine::ILLEGALL_OF_ORDERNUM);
                    return false;
                }

                if ($table[$key]['order_num'] == 0) {
                    array_splice($table, $key,1);
                }
                break;
            }
        }

        $table = self::updateorder($user_info['r_id'],$user_info['table_id'],$table);
        $message = [
            'table_order' => $table
        ];

        Utils::ShowMessage($message);
        return true;

    }

    //获取该桌订单
    function get_order($r_id,$table_id){

        if(!$this->__ConnectRedis($r_id)) {
            Utils::ShowError(ErrorDefine::GET_VERIFY_CODE_FAILED);
            return false;
        }

        $key = self::get_key($r_id,$table_id);
        $table = $this->redis_->get($key);
        if ($table === false) {
            $this->redis_->set($key,serialize([]));
            $table = $this->redis_->get($key);
        }
        $table = unserialize($table);
        return $table;
    }

    //更新订单
    function updateorder($r_id,$table_id,$table){

        if(!$this->__ConnectRedis($r_id)) {
            Utils::ShowError(ErrorDefine::GET_VERIFY_CODE_FAILED);
            return false;
        }

        $key = self::get_key($r_id,$table_id);
        $this->redis_->set($key,serialize($table));
        $table = $this->redis_->get($key);
        $table = unserialize($table);

        return $table;
    }


    //添加订单
    function OrderDishesV1($GetParams, $PostArray){

        $user_info = User::GetInfoByToken($GetParams['token']);
        if($user_info === false) {
            return false;
        }

        if (!isset($GetParams['recipe_id'])) {
            Utils::ShowError(ErrorDefine::SHORT_OF_RECIPEID);
            return false;
        }
        $check_num = $this->pdo->select('recipe_detail',array('d_num'),array('recipe_id' => $GetParams['recipe_id']));
        if ($check_num === false) {
            Utils::ShowError(ErrorDefine::SELECT_TABLE_FAILED);
            return false;
        }
        if ($check_num[0]['d_num'] == 0) {
            Utils::ShowError(ErrorDefine::DISHES_OVERSELL);
            return false;
        }

        if (empty($GetParams['order_num'])) {
            Utils::ShowError(ErrorDefine::SHORT_OF_PARAMETER);
            return false;
        }

        if ($GetParams['order_num']>$check_num[0]['d_num']) {
            Utils::ShowError(ErrorDefine::ILLEGALL_OF_ORDERNUM);
            return false;
        }

        $table = self::get_order($user_info['r_id'],$user_info['table_id']);
        if ($table === false) {
            return false;
        }

        $flag = false;
        foreach ($table as $key => $value) {
            if ($value['recipe_id'] == $GetParams['recipe_id']) {
                $table[$key]['order_num'] = $table[$key]['order_num'] + $GetParams['order_num'];
                if ($table[$key]['order_num'] > $check_num[0]['d_num']) {
                    Utils::ShowError(ErrorDefine::ILLEGALL_OF_ORDERNUM);
                    return false;
                }
                $flag = true;
                break;
            }
        }
        
        if ($flag === false) {
            $user = $this->pdo->select('users',array('user_pic','user_name'),array('user_id' => $user_info['user_id']));
            $recipe_info = $this->pdo->select('recipe',array('name','pic_url','type_id','price'),array('recipe_id' => $GetParams['recipe_id']));
            $d_info = $this->pdo->select('recipe_detail',array('d_num'),array('recipe_id' => $GetParams['recipe_id']));
            $type_name = $this->pdo->select('recipe_type',array('type_name'),array('type_id'=>$recipe_info[0]['type_id']));
            
            $dishes = [
                'recipe_id' => $GetParams['recipe_id'],
                'order_num' => $GetParams['order_num'],
                'name' => $recipe_info[0]['name'],
                'pic_url' => $recipe_info[0]['pic_url'],
                'user_pic' => $user[0]['user_pic'],
                'user_name' => $user[0]['user_name'],
                'user_id' => $user_info['user_id'],
                'price' => $recipe_info[0]['price'],
                'type_id' => $recipe_info[0]['type_id'],
                'type_name' => $type_name[0]['type_name'],
                'd_num' => $d_info[0]['d_num']
            ];
            array_push($table,$dishes);
        }
        
        $table = self::updateorder($user_info['r_id'],$user_info['table_id'],$table);

        $menu = new Menu();
        $menu_info = $menu->menu_detail($user_info);
        
        if ($menu_info === false) {
            return false;
        }
        $message = [
            'menu' => $menu_info
        ];
        Utils::ShowMessage($message);
        return true;
    }


    //确认订单提交到后台
    function ConfirmOrderV1($GetParams, $PostArray){

        $user_info = User::GetInfoByToken($GetParams['token']);
        if($user_info === false) {
            return false;
        }

        $table = self::get_order($user_info['r_id'],$user_info['table_id']);

        if ($table === false) {
            return false;
        }

        if (empty($table)) {
            Utils::ShowError(ErrorDefine::ORDER_DISH_FIRST);
            return false;
        }
        
        $all_recipe_id = '';
        foreach ($table as $key => $value) {
            $all_recipe_id .= ','.$value['recipe_id'];
        }
        $all_recipe_id = '('.substr($all_recipe_id, 1).')';

        $recipe_detail = $this->pdo->query('SELECT recipe_id,d_num FROM recipe_detail WHERE recipe_id IN '.$all_recipe_id.'');
        $recipe_wrong = [];
        foreach ($table as $key => $value) {
            foreach ($recipe_detail as $k => $v) {
                if ($v['recipe_id'] == $value['recipe_id'] ){
                    if ( $v['d_num'] >= $value['order_num']) {
                        continue;
                    }else{
                        $temp = [];
                        $temp = $value;
                        $temp['d_num'] = $v['d_num'];
                        array_push($recipe_wrong, $temp);
                    }
                }
            }
        }

        if (empty($recipe_wrong)) {
            $order = self::startcook($table,$user_info);
            if ($order === false) {
                return false;
            }
        }
        $message = [
            'order' => $order,
            'recipe_wrong' => $recipe_wrong
        ];
        Utils::ShowMessage($message);
        return true;
    }


    //提交订单，开始下厨
    private function startcook($table,$user_info){

        $field = ['order_id'];
        $params = [
            'r_id' => $user_info['r_id'],
            'table_id' => $user_info['table_id'],
            'status' => 0 
        ];
        $order_info = $this->pdo->select('orders',$field,$params);
        if (empty($order_info)) {
            date_default_timezone_set('PRC');
            $datetime = date('Y-m-d h:m:s');
            $params = [
                'user_id' => $user_info['user_id'],
                'create_time' => $datetime,
                'r_id' => $user_info['r_id'],
                'table_id' => $user_info['table_id']
            ];
            $order_id = $this->pdo->insert('orders',$params);
            
            if ($order_id === false) {
                Utils::ShowError(ErrorDefine::DATABASE_ERROR);
                return false;
            }
            $order_class = new Order();
            $order = $order_class->create_order($user_info);
            $sql = [];
            $sql[0] = "UPDATE `orders` SET `order` = '".$order."' WHERE order_id = ".$order_id."";
            $sql_num = 1;
        }else{
            $order_id = $order_info[0]['order_id'];
            $sql_num = 0;
        }
            
        foreach ($table as $key => $value) {
            $sql[$sql_num] = "INSERT order_detail (order_id,r_id,table_id,order_num,recipe_id,user_id)VALUES(".$order_id.",".$user_info['r_id'].",".$user_info['table_id'].",".$value['order_num'].",".$value['recipe_id'].",".$value['user_id'].")";
            $sql_num += 1;
            $sql[$sql_num] = "UPDATE recipe_detail SET d_num = d_num - ".$value['order_num']." WHERE recipe_id = ".$value['recipe_id']."";
            $sql_num += 1;
        }

        
        $res = $this->pdo->transaction($sql);
        if ($res === false) {
            Utils::ShowError(ErrorDefine::DATABASE_ERROR);
            return false;
        }

        $res = self::clear_table($user_info);
        if ($res === false) {
            return false;
        }
        return $order;
    }

    function ClearTableV1($GetParams, $PostArray){

        $user_info = User::GetInfoByToken($GetParams['token']);
        if($user_info === false) {
            return false;
        }

        $res = self::clear_table($user_info);
        if ($res === false) {
            return false;
        }

        Utils::ShowMessage();
        return true;
    }

    function clear_table($user_info){

        if(!$this->__ConnectRedis($r_id)) {
            Utils::ShowError(ErrorDefine::GET_VERIFY_CODE_FAILED);
            return false;
        }
        
        $key = self::get_key($user_info['r_id'],$user_info['table_id']);
        $table = $this->redis_->del($key);
        if ($table === false) {
            Utils::ShowError(ErrorDefine::DATABASE_ERROR);
            return false;
        }

        return true;
    }

    function SetTableInfoV1($GetParams, $PostArray){

        $user_info = User::GetInfoByToken($GetParams['token']);
        if($user_info === false) {
            return false;
        }

        if (empty($GetParams['users_num'])) {
            Utils::ShowError(ErrorDefine::ILLEGALL_USER_NUM);
            return false;
        }
        $note = '尚未备注';
        if (isset($GetParams['note'])) {
            $note = $GetParams['note'];
        }

        if(!$this->__ConnectRedis($user_info['r_id'])) {
            Utils::ShowError(ErrorDefine::GET_VERIFY_CODE_FAILED);
            return false;
        }

        $key = self::get_key($user_info['r_id'],$user_info['table_id']);
        $key = $key.'users';
        $value = [
            'users_num' => $GetParams['users_num'],
            'note' => $note
        ];
        $this->redis_->set($key,serialize($value));
        $table_info = $this->redis_->get($key);
        $table_info = unserialize($table_info);
        $message = [
            'users_num' => $table_info['users_num'],
            'note' => $table_info['note']
        ];
        Utils::ShowMessage($message);
        return true;
    }


    function TableInfoV1($GetParams, $PostArray){

        $user_info = User::GetInfoByToken($GetParams['token']);
        if($user_info === false) {
            return false;
        }

        $table_info = self::table_info($user_info);
        if (empty($table_info)) {
            $message = '';
        }else{
            $message = [
                'users_num' => $table_info['users_num'],
                'note' => $table_info['note']
            ];
        }
        Utils::ShowMessage($message);
        return true;
        
    }

    function table_info($user_info){

        if(!$this->__ConnectRedis($user_info['r_id'])) {
            Utils::ShowError(ErrorDefine::GET_VERIFY_CODE_FAILED);
            return false;
        }

        $key = self::get_key($user_info['r_id'],$user_info['table_id']);
        $key = $key.'users';
        $table_info = $this->redis_->get($key);
        $table_info = unserialize($table_info);
        if (empty($table_info)) {
            $table_info['users_num'] = 1;
            $table_info['note'] = '尚未备注';
        }
        return $table_info;
    }

    //连接redis
    private function __ConnectRedis($restaurant)
    {
        $region = CURRENT_REGION;
        $serverList = RedisConfig::$arrRedisServer[$region];
        $serverCount = count($serverList);
        if(0 == $serverCount) return false;

        $md5 = md5($restaurant);
        //将md5后四位转换成十进制
        $val = base_convert(substr($md5, -4), 16, 10);
        $idx = $val % $serverCount;
        
        $this->redis_ = new Redis();
        $this->redis_->connect($serverList[$idx],'6379');
        $this->redis_->auth(REDISPWD);

        return $this->redis_;

    }

    private function get_key($r_id,$table_id){
        $key = 'r'.$r_id.'t'.$table_id;
        return $key;
    }
    

}

?>